import React, { FC, useState, useEffect } from 'react';
import {
  Switch,
  withRouter,
  RouteComponentProps,
  Route,
} from 'react-router-dom';
import App from './App';
import Login from '@/pages/Login';

const Router: FC<RouteComponentProps> = ({ history }) => {
  const [isLogin, setIsLogin] = useState<boolean>(false);

  useEffect(() => {
    const username = window.sessionStorage.getItem('username');
    if (username) {
      setIsLogin(true);
    } else {
      setIsLogin(false);
      history.push('/login');
    }
  }, []);

  return (
    <Switch>
      {isLogin ? (
        <Route path="/" render={() => <App />}></Route>
      ) : (
        <Route
          path="/Login"
          render={() => <Login setIsLogin={setIsLogin} />}
        ></Route>
      )}
    </Switch>
  );
};

export default withRouter(Router);
